package boun.swe.bob.util;

import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Properties;

/**
 * This class is used for sending mail to users
 */
@Component
public class MailSender {

    /**
     * This method sends a mail
     *
     * @param recipients a string containing recipients
     * @param subject a string containing the mail subject
     * @param content a string containing the body of the mail 
     */
    public void send(String recipients, String subject, String content) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());


        Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");
                             


        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("fall2010g2@gmail.com", "fall2010g2pwd");
            }
        });

        MimeMessage message = new MimeMessage(session);
        try {
            message.setSender(new InternetAddress("fall2010g2@gmail.com"));
            message.setSubject(subject);
            message.setContent(content, "text/html");
            if (recipients.indexOf(',') > 0) {
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
            } else {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
            }

            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }


}